-module(db_homework_to_do).
-export([insert/2, get/1, get_with_offset/3, delete/2, delete_all/0]).
-include("records.hrl").


% Insert a homework in the homework_to_do table
insert(Student, Id) ->
	H = #homework_to_do {
		student = Student,
		id = Id
	},
	Fun = fun() ->
		mnesia:write(H)
	end,
	mnesia:transaction(Fun).
	

% Get all the homework IDs that the Student has to do
get(Student) ->
	Fun = fun() ->
		mnesia:read(homework_to_do, Student)
	end,
	mnesia:transaction(Fun).


% Get a list between [offset, offset+5] of the homework IDs that the Student has to do
get_with_offset(Student, Offset, TotalToDo) ->
	if TotalToDo =:= 0 ->
		{atomic, []};
	true -> 
		Homework = #homework_to_do{
			student = Student,
			id = '$1'
		},
		Fun = fun() ->
					Substract = TotalToDo - Offset,
					if 
						Offset > 9 ->
							{_, PreviousCont} = mnesia:select (homework_to_do, [{Homework, [], ['$1']}], 5, read),
							AuxList = create_list( (Offset div 5)-1 , []),
							LastCont = lists:foldl(fun(_,Cont) -> {_,NextCont} = mnesia:select(Cont), NextCont end, PreviousCont, AuxList),
							if
								Substract < 5 ->
									Aux = element(6, LastCont),
									Aux2 = setelement(3, Aux, Substract),
									ModifiedCont = setelement(6, LastCont, Aux2),
									mnesia:select(ModifiedCont);
								true -> 
									mnesia:select(LastCont)
							end;
						Offset > 4 ->
							{_, PreviousCont} = mnesia:select (homework_to_do, [{Homework, [], ['$1']}], 5, read),
							if
								Substract < 5 ->
									Aux = element(6, PreviousCont),
									Aux2 = setelement(3, Aux, Substract),
									ModifiedCont = setelement(6, PreviousCont, Aux2),
									mnesia:select(ModifiedCont);
								true -> 
									mnesia:select(PreviousCont)
							end;
						true ->
							if
								Substract < 5 ->
									mnesia:select (homework_to_do, [{Homework, [], ['$1']}], Substract, read);
								true ->
									mnesia:select (homework_to_do, [{Homework, [], ['$1']}], 5, read)
							end
					end
		end,

		{atomic, Results} = mnesia:transaction(Fun),
		case Results of
			'$end_of_table' ->
				[];
			{R, _} ->
				R
		end
	end.


create_list(0, L) -> L;
create_list(I, L) -> create_list(I-1, [I|L]).

	

% Deletes a entry of the homework_to_do table
delete(Student, Id) ->
	H = #homework_to_do {
		student = Student,
		id = Id
	},
	Fun = fun() ->
		mnesia:delete_object(H)
	end,
	mnesia:transaction(Fun).
	

% Delete all rows
delete_all() ->
	Fun = fun() ->
		Res = mnesia:select(homework_to_do, [{mnesia:table_info(homework_to_do, wild_pattern), [], ['$_']}]),
		lists:map(fun(X) -> mnesia:delete_object(X) end, Res)
	end,
	mnesia:transaction(Fun).
